import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Button, DatePicker, Modal, Input } from 'antd';
import type { FormInstance } from 'antd';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { PlusOutlined } from '@ant-design/icons';
import { useModel, history } from 'umi';
import Detail from './Detail';
import { getZcOrderList } from '@/services/order/api';
import { OptType } from '@/utils/constants';
import { showMsg, MsgType, formatDate, getDateValue, subtractDays, currentDate, isNull, isSupportSticky, isScroll } from '@/utils/utils';
import PermissionControl from '@/components/PermissionControl';
import { ModalForm, ProFormDatePicker, ProFormFieldSet, ProFormSelect } from '@ant-design/pro-form';
import BreadcrumbDept from '@/components/BreadcrumbDept';
import ChoicePatient from '@/components/ChoicePatient/list';
import '../onceOrder/style.less';

const OneTimeOrderList: React.FC = (props) => {
  const formRef = useRef<FormInstance>();
  const actionRef = useRef<ActionType>();
  const { info } = Modal;
  const { initialState } = useModel('@@initialState');

  // 表格选中行
  const [currentRow, setCurrentRow] = useState<ORDERAPI.OnceOrderItem>({});

  const [loading, setLoading] = useState(false);

  // 用于存储其他搜索条件
  const [otherParams, setOtherParams] = useState({ order_status: '', begin_date: '', end_date: '' });

  // 身份证/病案号
  const [inputNo, setInputNo] = useState('');

  // 当前选中的行编号，用于定位颜色
  const [clickRow, setClickRow] = useState('');

  // 详情弹窗
  const [detailVisible, setDetailVisible] = useState<boolean>(false);

  // 表单筛选项查询
  const forFormSearch = () => {
    setOtherParams({ order_status: '' });
    formRef.current?.submit();
  }

  // 列配置
  const columns: ProColumns<ORDERAPI.OnceOrderItem>[] = [
    {
      title: '下单时间',
      hideInTable: true,
      dataIndex: 'order_time',
      renderFormItem: () => {
        return <ProFormFieldSet wrapperCol={{ style: { width: '100%' } }}>
          <DatePicker allowClear={false} style={{ width: '100%' }} />
          <span style={{ padding: '0 5px' }}>-</span>
          <DatePicker allowClear={false} style={{ width: '100%' }} />
        </ProFormFieldSet>
      },
      order: 7,
    },
    {
      title: '身份证/住院号',
      dataIndex: 'input_no',
      hideInTable: true,
      renderFormItem: (_, { type }) => {
        if (type === 'form') {
          return null;
        }
        return (
          <ChoicePatient
            caseNoKey={initialState?.canAll ? 'out_case_no' : 'case_no'}
            showMore
            onChoice={(e) => setInputNo(e.visit_no)}
          />
        );
      },
      order: 7,
      formItemProps: {
        labelCol: { flex: '0 0 100px' }
      }
    },
    {
      title: '患者姓名',
      dataIndex: 'patient_name',
      hideInTable: true,
      renderFormItem: (_, { type }) => {
        if (type === 'form') {
          return null;
        }
        return (
          <Input className='mySearch' onPressEnter={forFormSearch} style={{ width: '100%' }} placeholder="输入患者姓名" />
        );
      },
      order: 6,
    },
    {
      title: '姓名',
      dataIndex: 'patient_name',
      search: false,
      width: 70
    },
    {
      title: '身份证/住院号',
      dataIndex: 'identity_no',
      search: false,
      className: 'wordbreak',
      width: 150,
      render: (_, record) => {
        return record.identity_no || record.admission_num || record.ic_card_no;
      }
    },
    {
      title: '订单号',
      dataIndex: 'order_id',
      width: 160,
      search: false
    },
    {
      title: '下单时间',
      dataIndex: 'create_time',
      search: false,
      width: isScroll ? 82 : 130,
      render: (_, record) => {
        return record.create_date + ' ' + record.create_time;
      }
    },
    {
      title: '开单科室',
      dataIndex: 'create_dept_name',
      width: 100,
      search: false
    },
    {
      title: '开单金额',
      dataIndex: 'total_price',
      width: 80,
      valueType: 'money',
      align: 'right',
      search: false
    },
    {
      title: '开单人',
      dataIndex: 'apply_oper_name',
      width: 70,
      renderFormItem: (_, { type }) => {
        if (type === 'form') {
          return null;
        }
        return (
          <Input className='mySearch' onPressEnter={forFormSearch} style={{ width: '100%' }} placeholder="输入开单人" />
        );
      },
      order: 3,
    },
    {
      title: '操作',
      valueType: 'option',
      // fixed: 'right',
      fixed: isSupportSticky() ? 'right' : false,
      width: 240,
      align: 'center',
      render: (_, record) =>
      <PermissionControl action_id="400405002">
              <a key="view" onClick={() => {
                setDetailVisible(true);
                setCurrentRow(record);
              }}>查看</a>
            </PermissionControl>
    }
  ];

  useEffect(() => {
    console.log('isSupportSticky', isSupportSticky());
    // 初始化搜索表单：下单时间默认查询当天的、搜索结果不包括：已完成、已作废
    formRef.current?.setFieldsValue({
      order_time: [
        subtractDays(30),
        '',
        currentDate(),
      ],
      not_status_list: ['E', 'F']
    });
    formRef.current?.submit();
  }, [])

  return (
    <PageContainer
      className="one-time-order-container"
      extra={[
        <BreadcrumbDept />
      ]}
      breadcrumb={{}}
    >
      <ProTable<ORDERAPI.OnceOrderItem, ORDERAPI.OnceOrderItem & { order_time?: string[]; begin_date?: string; end_date?: string; } & COMMON.PageParams>
        rowKey="order_id"
        actionRef={actionRef}
        formRef={formRef}
        bordered
        options={false}
        manualRequest={true}
        // polling={30000} // 每30秒刷新表格一次
        loading={loading}
        request={async (params) => {
          console.log('params', params);
          const { order_time } = params;
          if (order_time) {
            params.begin_date = order_time[0] && formatDate(order_time[0], 'YYYYMMDD');
            params.end_date = order_time[2] && formatDate(order_time[2], 'YYYYMMDD');
          }

          // 根据输入的判断是 就诊卡号、身份证号还是住院号  start
          if (inputNo.length >= 10 && inputNo.length < 15) { // 就诊卡号
            params.ic_card_no = inputNo;
            params.admission_num = '';
            params.identity_no = '';
          } else if (inputNo.length >= 15) { // 身份证号
            params.identity_no = inputNo;
            params.admission_num = '';
            params.ic_card_no = '';
          } else { // 住院号
            params.ic_card_no = '';
            params.identity_no = '';
            params.admission_num = inputNo;
          }
          // 根据输入的判断是 就诊卡号、身份证号还是住院号  end

          for (const prop in params) {
            if (!params[prop]) {
              delete params[prop];
            }
          }
          if (order_time && order_time[0] && order_time && order_time[2]) {
            if (getDateValue(order_time[0]) > getDateValue(order_time[2])) {
              showMsg('下单结束时间不能早于开始时间', MsgType.INFO);
              return;
            }
          }
          delete params.order_time;
          console.log('therParams', otherParams)
          // 如果用户单独点击了页面上的【查看已支付订单】【查看退款申请单】，请求接口的时候，则只传订单状态筛选，但页面上表单搜索信息则保留
          if (!isNull(otherParams.order_status)) {
            params = {
              ...otherParams,
              current: params.current,
              pageSize: params.pageSize,
            };
          }
          // setCache('once_order', JSON.stringify(params));
          setLoading(true);
          try {
            const data: ORDERAPI.OnceOrderItemList = await getZcOrderList(params);
            setLoading(false);
            return {
              data: data.record_list,
              success: true,
              total: data.sum_record_num
            }
          } catch (error) {
            setLoading(false);
            showMsg(error?.data?.errmsg);
            return {
              data: [],
              success: true,
              total: 0
            }
          }
        }}
        search={{
          span: 8,
          labelWidth: 70,
          collapsed: false,
          collapseRender: false,
          style: { padding: '0 12px' },
          optionRender: () => [
            <Button type='primary' onClick={() => {
              forFormSearch();
            }}>查询</Button>
          ]
        }}
        className='mytable onceOrderTable'
        toolBarRender={() => 
          <PermissionControl action_id="400405001">
            <Button
              onClick={() => {
                history.push({
                  pathname: '/order/zc-order/zc-bill',
                  query: {
                    type: OptType.ADD
                  }
                });
              }}
              icon={<PlusOutlined />}
              type="primary">
              开单
            </Button>
          </PermissionControl>
        }
        // scroll={{ x: window.innerWidth < 1400 ? 1250 : null }}
        pagination={{ showQuickJumper: true }}
        columns={columns}
        onRow={record => {
          return {
            onClick: event => { setClickRow(record.order_id) }, // 点击行
            onMouseEnter: event => { }, // 鼠标移入行
            onMouseLeave: event => { },
          };
        }}
        rowClassName={(record) => {
          return record.order_id === clickRow ? 'tableRowClick' : '' // 点击行，赋颜色
        }}
        scroll={{ x: 1000 }}
      />


      {
        // 查看弹窗
        detailVisible && <Detail
          handleModalVisible={setDetailVisible}
          record={currentRow}
        />
      }
    </PageContainer>
  );
};
export default OneTimeOrderList;
